package com.mall.seckill.job;

import com.mall.common.util.RespResult;
import com.mall.dw.feign.HotGoodsFeign;
import com.mall.seckill.service.ISeckillGoodsService;
import org.apache.shardingsphere.elasticjob.api.ShardingContext;
import org.apache.shardingsphere.elasticjob.simple.job.SimpleJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author Darren
 * @date 2022-10-14 16:15
 * Description：
 */
@Component
public class HotGoodsJob implements SimpleJob {
    @Autowired
    private HotGoodsFeign hotGoodsFeign;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ISeckillGoodsService seckillGoodsService;

    @Value("${hot.size}")
    private Integer size;
    @Value("${hot.hour}")
    private Integer hour;
    @Value("${hot.max}")
    private Integer max;

    @Override
    public void execute(ShardingContext shardingContext) {
        String[] urls = isolationList();
        RespResult<List<Map<String, String>>> respResult = hotGoodsFeign.searchHotGoods(size, hour, urls, max);
        List<Map<String, String>> data = respResult.getData();
        if (data != null) {
            for (Map<String, String> map : data) {
                //处理请求路径
                String uri = uriReplace(map.get("uri"), 1);
                System.out.println("查询到的热门商品ID：" + uri);
                // 秒杀商品隔离
                seckillGoodsService.isolation(uri);
            }
        }
    }

    public String[] isolationList() {
        Set<String> ids = redisTemplate.boundHashOps("HotSeckillGoods").keys();
        if (ids == null || ids.size() == 0)
            return new String[0];
        String[] allIds = new String[ids.size()];
        ids.toArray(allIds);
        // uri地址处理
        for (int i = 0; i < allIds.length; i++) {
            allIds[i] = uriReplace(allIds[i], 2);
        }
        System.out.println("==========> allIds:" + Arrays.toString(allIds));
        return allIds;
    }

    /**
     * uri处理
     *
     * @param uri
     * @param type 1 uri表示商品请求路径， 2 uri表示商品ID
     * @return
     */
    public String uriReplace(String uri, Integer type) {
        switch (type) {
            case 1:
                return uri.replace("/msitems/", "").replace(".html", "");
            case 2:
                return "/msitems/" + uri + ".html";
            default:
                return "/msitems/" + uri + ".html";
        }
    }
}
